//
//  HYMainTabBar.swift
//  iOSWeibo
//
//  Created by why on 16/7/18.
//  Copyright © 2016年 王浩宇. All rights reserved.
//

import UIKit

class HYMainTabBar: UITabBar {
    
    var composeCallback: (() -> Void)?

    lazy var composeButton: UIButton = {
        let button = UIButton(type: UIButtonType.Custom)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        self.addSubview(button)
        
        button.addTarget(self, action: "composeClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
        
    }()
    
    let itemCount: Int = 5
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        let newItemWidth = self.frame.width / CGFloat(itemCount)
        
        var index = 0
        for item in self.subviews {
            
            let cls = NSClassFromString("UITabBarButton")!
            if item.isKindOfClass(cls) {
                
                item.frame = CGRect(x: CGFloat(index) * newItemWidth, y: 0, width: newItemWidth, height: self.frame.height)
                
                index++
                
                if index == 2 {
                    index++
                }
            }
        }
        
        composeButton.frame = CGRect(x: 2 * newItemWidth, y: 0, width: newItemWidth, height: self.frame.height)
    }
    
    func composeClick() {
        composeCallback?()
    }
}
